# @File    : kill_ota.py
# @Project : Airtest_JBL
from common.logUtil import info_a, warning_a
from Android.upgrade import Upgrade
from airtest.core.api import *
import re


class KillOta(Upgrade):

    h_version = Upgrade.location['h_version']
    l_version = Upgrade.location['l_version']
    test_device = Upgrade.location['device']

    surplus = "^剩余 [1-5] 分钟"
    process = "^.*%"

    def ota_kill_app(self, num):
        i = 1
        while i < int(num)+1:
            version = self.check_version()
            if version == self.l_version:
                self.is_low(i, version)
                self.check_upgrade(i)
                if self.test_device == "耳机":
                    version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
                elif self.test_device == "充电盒":
                    version = self.poco(textMatches=f"{self.case}").get_text()[6:]
                if version == self.h_version:
                    warning_a(f"第 {i} 次测试后耳机版本为: {version}")
                    sleep(2)
                    warning_a("耳机将降级后继续测试!")
                    i -= 1
            elif version == self.h_version:
                self.is_height(i, version)
                i -= 1
            else:
                warning_a(f"当前耳机版本: {version} 错误,重新启动APP后再次查看是否正确!")
                i -= 1
            if i < num:
                sleep(1)
                stop_app("jbl.stc.com.debug")
                sleep(2)
                start_app("jbl.stc.com.debug")
                sleep(1)
            i += 1
        sleep(1)
        info_a(f"中断升级测试完成, 共压测 {i - 1} 次, 其中 PASS {self.pass_num} 次, FAIL {self.fail_num} 次, FAIL的轮数为{self.fail_list}")
        self.fail_list.clear()

    def is_height(self, i, version):
        Upgrade.page_back(self)
        Upgrade.select_version(self, version, self.test_device)
        self.start_ota(i)
        self.ota_process(i, version)
        sleep(1)

    def is_low(self, i, version):
        Upgrade.page_back(self)
        Upgrade.select_version(self, version, self.test_device)
        self.start_ota(i)

    def start_ota(self, i):
        # touch(v=(550, 715))
        Upgrade.poco("android.widget.FrameLayout").offspring("jbl.stc.com.debug:id/grid_view_dashboard").child(
            "android.widget.LinearLayout")[0].offspring(
            "jbl.stc.com.debug:id/image_view_item_connected_before_device_icon").click()
        self.poco(text="Others").click()
        swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
        self.poco(text="支持").click()
        if self.test_device == "耳机":
            version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
            self.poco(text="软件").click()
        else:
            version = self.poco(textMatches=f"{self.case}").get_text()[6:]
            self.poco(text="智能保护盒").click()
        self.poco(text="更新").refresh()
        self.poco(text="更新").click()
        if version == self.h_version:
            info_a("降级开始...")
        elif version == self.l_version:
            info_a(f"第 {i} 次测试开始...")

    def check_upgrade(self, i):
        while True:
            if self.poco(text="重试").exists():
                self.poco(text="重试").click()
                sleep(1)
                self.poco(text="更新").click()
            if self.poco(textMatches=f"{self.surplus}").exists():
                result = self.is_install(self.poco(textMatches=f"{self.process}").get_text())
                if result:
                    while True:
                        if self.poco(text="更新成功").exists():
                            self.poco(text="完成").click()
                            break
                    break
                else:
                    sleep(0.5)
                    stop_app("jbl.stc.com.debug")
                    sleep(2)
                    start_app("jbl.stc.com.debug")
                    sleep(1)
                    other = self.poco(text="Others").wait(15)
                    if other.exists():
                        other.click()
                        swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
                        self.poco(text="支持").click()
                    if self.test_device == "耳机":
                        version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
                    else:
                        version = self.poco(textMatches=f"{self.case}").get_text()[6:]
                    if version == self.l_version:
                        info_a(f"中断升级后耳机版本为: {version}")
                        sleep(2)
                        info_a(f"第 {i} 次中断升级测试结果为: PASS")
                        sleep(1)
                        self.pass_num += 1
                    else:
                        info_a(f"中断升级后耳机版本为: {version}")
                        sleep(2)
                        info_a(f"第 {i} 次中断升级测试结果为: FAIL")
                        sleep(1)
                        self.fail_num += 1
                        self.fail_list.append(i)
                    break

    # 升级过程
    def ota_process(self, i, version):
        while True:
            if self.poco(text="更新成功").exists():
                self.poco(text="完成").click()
                if self.test_device == "耳机":
                    version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
                elif self.test_device == "充电盒":
                    version = self.poco(textMatches=f"{self.case}").get_text()[6:]
                self.check_after_version(i, version)
                break
            # 更新失败处理
            if self.poco(text="更新失败").exists():
                self.poco(text="取消").click()
                version = self.ex.check_fail(self.earbud)
                self.check_after_version(i, version)
                self.fail_num += 1
                self.fail_list.append(i)
                info_a("安装最后一分钟时更新失败")
                sleep(1)
                break
            if self.poco(text="重试").exists():
                self.poco(text="重试").click()
                sleep(1)
                self.poco(text="更新").click()

    # 根据升级后的版本来进行后续操作
    def check_after_version(self, i, version):
        if version == self.h_version:
            info_a(f"升级成功...")
            sleep(2)
            info_a(f"升级后的版本为: {version}")
        else:
            stop_app("jbl.stc.com.debug")
            time.sleep(2)
            start_app("jbl.stc.com.debug")
            other = self.poco(text="Others").wait(15)
            if other.exists():
                other.click()
                swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
                self.poco(text="支持").click()
                if self.test_device == "耳机":
                    version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
                elif self.test_device == "充电盒":
                    version = self.poco(textMatches=f"{self.case}").get_text()[6:]
                if version == self.l_version:
                    info_a(f"降级成功...")
                    sleep(2)
                    info_a(f"降级后的版本为: {version}")

    # 检查当前下载进度(如果当前下载进度大于等于96%，则不点击取消，等待升级完成)
    def is_install(self, t):
        pattern = "^9[5-9]%"
        if re.match(pattern, t):
            return True
        else:
            return False
